package com.sdp.irrigation.controller;


import java.time.LocalDateTime;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.sdp.core.bizc.db.Query;
import com.sdp.core.bizc.utils.UniqueCheckTools;
import com.sdp.core.bizc.vo.DataCenter;
import com.sdp.core.bizc.vo.Result;
import com.sdp.irrigation.cache.IrrigationCleanCache;
import com.sdp.irrigation.db.irrigation_project.service.IIrrigationProjectService;
import com.sdp.irrigation.entity.IrrigationProject;


/**
 * <p>
 * 项目台账信息 前端控制器
 * </p>
 *
 * @author zsp
 * @since 2024-12-14
 */
@RestController
@RequestMapping("/IrrigationProjectController")
public class IrrigationProjectController {

	@Autowired
	private IIrrigationProjectService iIrrigationProjectService;
	
	@Autowired
	private Query query;
	
	@Autowired
	private UniqueCheckTools uniqueCheckTools;	
	
	@Autowired
	private IrrigationCleanCache irrigationCleanCache;
	
	@PostMapping(value = "/page")
	public Result<?> page(@RequestBody DataCenter dataCenter) {
		return Result.ok(query.page(iIrrigationProjectService, IrrigationProject.class, dataCenter));
	}
	
	@PostMapping(value = "/save")
	@Transactional(rollbackFor=Exception.class)
	public Result<?> save(@RequestBody IrrigationProject project) {
		if(project==null) {
			return Result.error("项目信息为空");
		}
		if(StringUtils.isEmpty(project.getKeyId())) {
			Result<?> r = uniqueCheckTools.isUniqueSingle(iIrrigationProjectService, IrrigationProject.class, new String[] {"projectNo","projectName"}, "keyId", project, null, false);
			if(r==null || !r.isSuccess()) {
				return Result.error("项目名称和编号不能重复");
			}
			project.setCreateTime(LocalDateTime.now());
			project.setUpdateTime(LocalDateTime.now());
			iIrrigationProjectService.save(project);
		}else {
			Result<?> r = uniqueCheckTools.isUniqueSingle(iIrrigationProjectService, IrrigationProject.class, new String[] {"projectNo","projectName"}, "keyId", null, project, false);
			if(r==null || !r.isSuccess()) {
				return Result.error("项目名称和编号不能重复");
			}
			project.setUpdateTime(LocalDateTime.now());
			iIrrigationProjectService.updateById(project);
		}
		
		//更新缓存
		irrigationCleanCache.cleanProjectCache();
		return Result.ok();
	}
	
}

